/* ========== 通用 CRUD ========== */
const STORE = {
  key: 'demo',               // localStorage 根键
  init(){
    const raw = localStorage.getItem(this.key);
    if(!raw) this.save({user:[], article:[], comment:[]});
  },
  get(){
    return JSON.parse(localStorage.getItem(this.key));
  },
  save(obj){
    localStorage.setItem(this.key, JSON.stringify(obj));
  },
  /* 增 */
  add(table, row){
    const db = this.get();
    row.id = Date.now();      // 简单自增 ID
    db[table].push(row);
    this.save(db);
    return row;
  },
  /* 查 - 单条 */
  find(table, id){
    return this.get()[table].find(v => v.id == id);
  },
  /* 查 - 全部 */
  all(table){
    return this.get()[table];
  },
  /* 改 */
  update(table, id, newVal){
    const db = this.get();
    const idx = db[table].findIndex(v => v.id == id);
    if(idx === -1) return false;
    db[table][idx] = { ...db[table][idx], ...newVal };
    this.save(db);
    return true;
  },
  /* 删 */
  remove(table, id){
    const db = this.get();
    db[table] = db[table].filter(v => v.id != id);
    this.save(db);
  }
};

STORE.init();   // 第一次初始化
